package net.bwie.realtime.dwd.douyin.logs.bean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class TransactionAccumulator implements Serializable {
    private String liveRoomId;
    private Set<String> uniqueUsers;
    private Set<String> uniqueOrders;
    private long orderCount;
    private long userCount;
    private String startTime;    // 开始时间（字符串格式）
    private String endTime;      // 结束时间（字符串格式）
    private transient SimpleDateFormat sdf;

    public TransactionAccumulator(String liveRoomId, SimpleDateFormat sdf) {
        this.liveRoomId = liveRoomId;
        this.uniqueUsers = new HashSet<>();
        this.uniqueOrders = new HashSet<>();
        this.orderCount = 0;
        this.userCount = 0;
        this.startTime = "N/A";
        this.endTime = "N/A";
        this.sdf = sdf;
    }

    public void addOrder(String orderId, String userId, Long timestamp) {
        // 更新订单统计
        if (orderId != null && uniqueOrders.add(orderId)) {
            orderCount++;
        }

        // 更新用户统计
        if (userId != null && uniqueUsers.add(userId)) {
            userCount++;
        }

        // 更新时间范围（转换为字符串）
        if (timestamp != null) {
            String timeStr = sdf.format(new Date(timestamp));

            if (startTime!=null || timestamp < parseTimeToLong(startTime)) {
                startTime = timeStr;
            }
            if (endTime!=null || timestamp > parseTimeToLong(endTime)) {
                endTime = timeStr;
            }
        }
    }

    // 将字符串时间转换回long类型用于比较
    private long parseTimeToLong(String timeStr) {
        if ("N/A".equals(timeStr)) {
            return 0L;
        }
        try {
            return sdf.parse(timeStr).getTime();
        } catch (Exception e) {
            return 0L;
        }
    }

    @Override
    public String toString() {
        return String.format("直播间ID: %s, 订单数: %d, 订单人数: %d, 开始时间: %s, 结束时间: %s",
                liveRoomId, orderCount, userCount, startTime, endTime);
    }

    // Getter方法
    public String getLiveRoomId() { return liveRoomId; }
    public long getOrderCount() { return orderCount; }
    public long getUserCount() { return userCount; }
    public String getStartTime() { return startTime; }
    public String getEndTime() { return endTime; }
}
